package controllers

import (
	"encoding/json"
	"errors"
	"gitee.com/lzqysoft/ims/models"
	"strings"

	"github.com/astaxie/beego"
	"time"
)

// ImsProfessorGroupController operations for ImsProfessorGroup
type ImsProfessorGroupController struct {
	CommonController
}

// URLMapping ...
func (c *ImsProfessorGroupController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Put", c.Put)
	c.Mapping("Delete", c.Delete)
	c.Mapping("QueryGroupByDept", c.QueryGroupByDept)
	c.Mapping("UpdateProfessorGroup", c.UpdateProfessorGroup)
	c.Mapping("DeleteProfessorGroupList", c.DeleteProfessorGroupList)
	c.Mapping("QueryUserByImsProfessorGroup", c.QueryUserByImsProfessorGroup)
	c.Mapping("UpdateProfessorGroupMember", c.UpdateProfessorGroupMember)
	c.Mapping("SetLeader", c.SetLeader)
	c.Mapping("GetAllGroup", c.GetAllGroup)
	c.Mapping("QueryProfessorGroupUsers", c.QueryProfessorGroupUsers)
}

// Post ...
// @Title Post
// @Description create ImsProfessorGroup
// @Param	body		body 	models.ImsProfessorGroup	true		"body for ImsProfessorGroup content"
// @Success 201 {int} models.ImsProfessorGroup
// @Failure 403 body is empty
// @router / [post]
func (c *ImsProfessorGroupController) Post() {
	user := c.User
	tdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	m := models.NewImsProfessorGroup()
	if err = json.Unmarshal(tdata, m); err != nil {
		beego.Debug(err)
	}
	m.CId, m.UId, m.Creater, m.Updater = user.Id, user.Id, user.Abbr, user.Abbr
	if _,err = models.AddImsProfessorGroup(m); err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	c.RetSuccess(nil)
}

// GetOne ...
// @Title Get One
// @Description get ImsProfessorGroup by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.ImsProfessorGroup
// @Failure 403 :id is empty
// @router /:id [get]
func (c *ImsProfessorGroupController) GetOne() {
	idStr := c.Ctx.Input.Param(":id")
	//id, _ := strconv.Atoi(idStr)
	v, err := models.GetImsProfessorGroupById(idStr)
	if err != nil {
		c.Data["json"] = err.Error()
	} else {
		c.Data["json"] = v
	}
	c.ServeJSON()
}

// GetAll ...
// @Title Get All
// @Description get ImsProfessorGroup
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.ImsProfessorGroup
// @Failure 403
// @router / [get]
func (c *ImsProfessorGroupController) GetAll() {
	var fields []string
	var sortby []string
	var order []string
	var query = make(map[string]string)
	var limit int64 = 10
	var offset int64

	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	// query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}

	l, err := models.GetAllImsProfessorGroup(query, fields, sortby, order, offset, limit)
	if err != nil {
		c.Data["json"] = err.Error()
	} else {
		c.Data["json"] = l
	}
	c.ServeJSON()
}

// Put ...
// @Title Put
// @Description update the ImsProfessorGroup
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.ImsProfessorGroup	true		"body for ImsProfessorGroup content"
// @Success 200 {object} models.ImsProfessorGroup
// @Failure 403 :id is not int
// @router /:id [put]
func (c *ImsProfessorGroupController) Put() {
	idStr := c.Ctx.Input.Param(":id")
	//id, _ := strconv.Atoi(idStr)
	v := models.ImsProfessorGroup{Id: idStr}
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil {
		if err := models.UpdateImsProfessorGroupById(&v); err == nil {
			c.Data["json"] = "OK"
		} else {
			c.Data["json"] = err.Error()
		}
	} else {
		c.Data["json"] = err.Error()
	}
	c.ServeJSON()
}


// UpdateProfessorGroup ...
// @Title UpdateProfessorGroup
// @Description UpdateProfessorGroup
// @Param	body		body 	models.ImsProfessorGroup	true		"body for ImsProfessorGroup content"
// @Success 200 {object} models.ImsProfessorGroup
// @Failure body
// @router /UpdateProfessorGroup [post]
func (c *ImsProfessorGroupController) UpdateProfessorGroup()  {
	user := c.User
	tdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	var m models.ImsProfessorGroup
	if err = json.Unmarshal(tdata, &m); err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	m.UId = user.Id
	m.Updater = user.Abbr
	m.Utime = time.Now()
	if err = models.UpdateImsProfessorGroupById(&m);err != nil {
		beego.Debug(err)
		c.RetError(ErrDatabase)
	}
	c.RetSuccess(nil)
}
// Delete ...
// @Title Delete
// @Description delete the ImsProfessorGroup
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /:id [delete]
func (c *ImsProfessorGroupController) Delete() {
	idStr := c.Ctx.Input.Param(":id")
	//id, _ := strconv.Atoi(idStr)
	if err := models.DeleteImsProfessorGroup(idStr); err == nil {
		c.Data["json"] = "OK"
	} else {
		c.Data["json"] = err.Error()
	}
	c.ServeJSON()
}


// QueryGroupByDept ...
// @Title QueryGroupByDept
// @Description QueryGroupByDept
// @Param	body		body 	models.ImsProfessorGroup	true		"body for ImsProfessorGroup content"
// @Success 200 {Array} []models.ImsProfessorGroup
// @Failure 403 body
// @router /QueryGroupByDept/:id [get]
func (c *ImsProfessorGroupController) QueryGroupByDept () {
	//tdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	//if err != nil {
	//	c.RetError(ErrToken)
	//}
	//var d models.Dept
	//if err = json.Unmarshal(tdata, &d); err != nil {
	//	beego.Debug(err)
	//	c.RetError(ErrInputData)
	//}
	//id := c.GetString("id")
	id := c.Ctx.Input.Param(":id")
	beego.Debug("ID", id)
	l, err := models.GetImsProfessorGroupByDept(id)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrDatabase)
	}
	c.RetSuccess(l)
}


// DeleteProfessorGroupList ...
// @Title DeleteProfessorGroupList
// @Description DeleteProfessorGroupList
// @Param	bodys		bodys 	[]models.ImsProfessorGroup	true		"body for ImsProfessorGroup content"
// @Success 200
// @Failure 403 body
// @router /DeleteProfessorGroupList [post]
func (c *ImsProfessorGroupController) DeleteProfessorGroupList() {
	user := c.User
	tdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrToken)
	}
	var l []models.ImsProfessorGroup
	if err = json.Unmarshal(tdata, &l); err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	if err = models.SoftDeleteImsProfessorGroupByDept(l, user); err != nil {
		beego.Debug(err)
		c.RetError(ErrDatabase)
	}
	c.RetSuccess(nil)
}

// QueryUserByImsProfessorGroup ...
// @Title QueryUserByImsProfessorGroup
// @Description QueryUserByImsProfessorGroup
// @Param	bodys		bodys 	[]models.ImsProfessorGroup	true		"body for ImsProfessorGroup content"
// @Success 200
// @Failure 403 body
// @router /QueryUserByImsProfessorGroup [post]
func (c *ImsProfessorGroupController) QueryUserByImsProfessorGroup() {
	tdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	var m models.ImsProfessorGroup
	if err = json.Unmarshal(tdata, &m); err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	if l, err := models.QueryUserByImsProfessorGroup(m.Id); err != nil {
		beego.Debug(err)
		c.RetError(ErrDatabase)
	} else  {
		c.RetSuccess(l)
	}
}

// ProfessorGroupParams 修改专家组成员参数
type ProfessorGroupParams struct {
	UserArray []string
	ProfessorGroupId string
}

// UpdateProfessorGroupMember ...
// @Title UpdateProfessorGroupMember
// @Description UpdateProfessorGroupMember
// @Param	bodys		bodys 	ProfessorGroupParams	true		"body for ImsProfessorGroup content"
// @Success 200
// @Failure 403 body
// @router /UpdateProfessorGroupMember [post]
func (c *ImsProfessorGroupController) UpdateProfessorGroupMember() {
	tdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	var params ProfessorGroupParams
	if err = json.Unmarshal(tdata, &params); err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	if err = models.UpdateProfessorGroupMember(params.ProfessorGroupId, params.UserArray); err != nil {
		beego.Debug(err)
		c.RetError(ErrDatabase)
	}
	c.RetSuccess(nil)
}


// SetLeader ...
// @Title SetLeader
// @Description SetLeader
// @Param	bodys		bodys 	ProfessorGroupParams	true		"body for ImsProfessorGroup content"
// @Success 200
// @Failure 403 body
// @router /SetLeader [post]
func (c *ImsProfessorGroupController) SetLeader () {
	tdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	var params ProfessorGroupParams
	if err = json.Unmarshal(tdata, &params); err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	if len(params.UserArray) != 1 {
		beego.Debug("参数错误")
		c.RetError(ErrInputData)
	}
	if err = models.SetLeader(params.UserArray[0], params.ProfessorGroupId); err != nil {
		beego.Debug(err)
		c.RetError(ErrDatabase)
	}
	c.RetSuccess(nil)
}


// GetAllGroup ...
// @Title GetAllGroup
// @Description GetAllGroup
// @Success 200
// @Failure 403 token error
// @router /GetAllGroup [get]
func (c *ImsProfessorGroupController) GetAllGroup () {
	if l, err := models.GetAllImsProjectWithStatus(); err != nil {
		beego.Debug(err)
		c.RetError(ErrDatabase)
	} else {
		//beego.Debug(l)
		c.RetSuccess(l)
	}
}


// QueryProfessorGroupUsers ...
// @Title QueryProfessorGroupUsers
// @Description QueryProfessorGroupUsers
// @Param	id		path 	QueryParams	true		"QueryProfessorGroupUsers"
// @Success 200 {string} query success!
// @Failure 403 id is empty
// @router /QueryProfessorGroupUsers [post]
func (c *ImsProfessorGroupController) QueryProfessorGroupUsers () {
	tdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	var params QueryParams
	if err = json.Unmarshal(tdata, &params); err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	groupId, ok := params.Query["ProfessorGroupId"]
	if !ok {
		beego.Debug("参数有误")
		c.RetError(ErrInputData)
	}
	l, err := models.GetProfessorGroupUsers(groupId)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrDatabase)
	}
	c.RetSuccess(l)
}